﻿using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace NuGet.MSBuild.Tools
{
    public class GetAssemblyVersion : Task
    {
        [Required]
        public string FileName { get; set; }

        [Output]
        public string Version { get; set; }

        public override bool Execute()
        {
            if (File.Exists(this.FileName))
            {
                string assemblyVersion = null;

                AssemblyName name = AssemblyName.GetAssemblyName(this.FileName);
                if (name != null)
                {
                    assemblyVersion = name.Version.ToString();
                }

                FileVersionInfo version = FileVersionInfo.GetVersionInfo(this.FileName);
                if (version != null && version.ProductVersion != version.FileVersion)
                {
                    assemblyVersion = version.ProductVersion;
                }

                this.Version = assemblyVersion;
            }

            return true;
        }
    }
}
